﻿using DiLe.Mes.Application.Common;
using DiLe.Mes.Cloud.Controllers.SystemManage.Organization.Dto;
using DiLe.Mes.Cloud.Controllers.SystemManage.Organization.Parameters;
using DiLe.Mes.Model.Common.Organization.Entity;

namespace DiLe.Mes.Cloud.Controllers.SystemManage.Organization {
    /// <summary>
    /// 用户
    /// </summary>
    [ApiExplorerSettings(GroupName = ApiCloudGroupConst.Organization)]
    public class UserController : ApiBaseController {
        /// <summary>
        /// 
        /// </summary>
        private readonly OrganizationClient _organizationClient;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="organizationClient"></param>
        public UserController(OrganizationClient organizationClient) {
            _organizationClient = organizationClient;
        }


        /// <summary>
        /// 重置密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> ResetPassword(List<long> ids) {
            await _organizationClient.ResetPasswordAsync(ids);
            return Success();
        }
        /// <summary>
        /// 获取当前人员
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetCurrentUserInfo() {
            var acount = AppHelper.LoginUserInfo!.Account!;
            UserEntity res = new() {
                Account = acount,
                Name = "超级管理员"
            };
            if (acount != "admin") {
                res = await _organizationClient.GetUserByAccountAsync(acount);
                if (res != null) {
                    var role = await _organizationClient.GetUserRoleByUserIdAsync(res.Id);
                    if (role != null) {
                        var permission = await _organizationClient.GetPermissionByRoleIdAsync(role.RoleId);
                        res.ExtJson.Add("PowerSetJson", permission?.PowerSetJson);
                        res.ExtJson.Add("RoleId", permission?.RoleId);
                    }
                }
            }
            return Success(res);
        }
        /// <summary>
        /// 获取人员列表
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetUserListByOrgId(long orgId) {
            var list = await _organizationClient.GetUserListByOrgIdAsync(orgId);
            return Success(list);
        }
        /// <summary>
        /// 获取人员列表
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetUserListByIds(List<long> ids) {
            var list = await _organizationClient.GetUserListByIdAsync(ids);
            await FillUserExjosn(list);
            return Success(list);
        }
        /// <summary>
        /// 获取人员列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetUserList(UserQueryParameter parameter) {
            var whereExpression = Expressionable.Create<UserEntity>();
            if (!parameter.Keyword.IsNullOrEmpty()) {
                whereExpression.Or(p => p.Name.Contains(parameter.Keyword!));
                whereExpression.Or(p => p.Code.Contains(parameter.Keyword!));
            }
            if (parameter.OrgId > 0) {
                whereExpression.And(p => p.DepartmentId == parameter.OrgId);
            }
            if (parameter.Pagination == null) {
                var res = await _organizationClient.GetUserListAsync(whereExpression.ToExpression());
                await FillUserExjosn(res);
                return Success(res);
            } else {
                var res = await _organizationClient.GetUserPageListAsync(whereExpression.ToExpression(), parameter.Pagination);
                await FillUserExjosn(res.Record);
                return Success(res);
            }
        }
        /// <summary>
        /// 获取人员信息 -id
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetUserInfo(long id) {
            UserEntity res;
            if (id == 0) {
                res = new() {
                    Account = "admin",
                    Name = "超级管理员"
                };
            } else {
                res = await _organizationClient.GetUserByIdAsync(id);
                await FillUserExjosn(new List<UserEntity> { res });
            }
            return Success(res);
        }

        /// <summary>
        /// 保存人员信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> SaveUser(UserEntity model) {
            await _organizationClient.SaveUserAsync(model);
            return Success();
        }
        /// <summary>
        /// 删除人员信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> DeleteUser(List<long> ids) {
            var res = await _organizationClient.DeleteUserAsync(ids);
            if (res == 0) {
                throw ApiFriendlyException.OhBus(1111, "删除失败！");
            }
            return Success();
        }
        /// <summary>
        /// 更新人员状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> UpdateUserStatus(CommomParameter parameter) {
            var res = await _organizationClient.UpdateUserStatusAsync(parameter.Ids, parameter.Status);
            return Success(res);
        }

        #region 部门-人员
        /// <summary>
        /// 获取人员树
        /// </summary>
        [HttpGet]
        public async Task<ApiResult<UserTreeModel>> GetUserTree() {
            var orgList = await _organizationClient.GetOrganizationListAsync();
            var userList = await _organizationClient.GetUserListAsync();
            var root = orgList.FirstOrDefault(p => p.ParentId == 0);
            var model = new UserTreeModel {
                Id = root?.Id,
                Name = root?.Name
            };
            var childrens = GetChildUserTrees(root?.Id, orgList, userList);
            model.Children.AddRange(childrens);
            var users = userList.Where(p => p.DepartmentId == root?.Id)
                                .Select(x => new UserTreeModel { Id = x.Id, Name = x.Name, Type = 2, OrgName = root!.Name })
                                .ToList();
            model.Children.AddRange(users);
            return Success(model);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="orgList"></param>
        /// <param name="userList"></param>
        /// <returns></returns>
        private List<UserTreeModel> GetChildUserTrees(long? parentId, List<OrganizationEntity> orgList, List<UserEntity> userList) {
            var list = new List<UserTreeModel>();
            var orgArr = orgList.Where(p => p.ParentId == parentId).ToList();
            foreach (var org in orgArr) {
                var model = new UserTreeModel {
                    Id = org?.Id,
                    Name = org?.Name
                };
                list.Add(model);
                var childrens = GetChildUserTrees(org?.Id, orgList, userList);
                model.Children.AddRange(childrens);
                var users = userList.Where(p => p.DepartmentId == org?.Id)
                                    .Select(x => new UserTreeModel { Id = x.Id, Name = x.Name, Type = 2, OrgName = org!.Name })
                                    .ToList();
                model.Children.AddRange(users);
            }
            return list;
        }
        #endregion

        #region 其他方法
        /// <summary>
        /// 
        /// </summary>
        /// <param name="users"></param>
        private async Task FillUserExjosn(List<UserEntity> users) {
            if (!users.Any()) {
                return;
            }
            var orgids = users.Where(p => p.DepartmentId > 0).Select(p => p.DepartmentId).Distinct().ToList();
            var orgList = await _organizationClient.GetOrganizationListAsync(orgids);
            var jobpostid = users.Select(p => p.JobPostId).Distinct().ToList();
            var jobpostList = await _organizationClient.GetJobPostListAsync(jobpostid);

            foreach (var item in users) {
                var org = orgList?.FirstOrDefault(p => p.Id == item.DepartmentId);
                item.ExtJson.Add("DepartmentName", org?.Name);
                var jobpost = jobpostList?.FirstOrDefault(p => p.Id == item.JobPostId);
                item.ExtJson.Add("JobPostName", jobpost?.Name);
            }
        }
        #endregion
    }
}
